package com.android.rate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.widget.Toast;

import com.android.data.DatabaseHelper;
import com.android.entities.HistoryEntry;

public class HistoryHelper {
	
	private static final String TABLE_NAME = "history";	 
	private Context context;
	private SQLiteDatabase db;
	private DatabaseHelper openHelper;
	private SQLiteStatement insertStmt;
	private static final String INSERT = "insert into " + TABLE_NAME + "(_id, name, " +
			"rate, recommended, sent, _date) values (?, ?, ?, ?, ?, ?)";
	
	public HistoryHelper(Context context) {
		this.context = context;
		this.openHelper = new DatabaseHelper(this.context);
		this.db = openHelper.getWritableDatabase();
		this.insertStmt = this.db.compileStatement(INSERT);
	}
	 
	public void close() {
		this.openHelper.close();
	}
	
	public long insert(String id, String name, int rate, int recommended, int sent, String date) { 
		String mName = (name != null && name.length() > 0) ? name : "-";
		String mDate = (date != null && date.length() > 0) ? date : "-";
		
		this.insertStmt.bindString(1, id);
		this.insertStmt.bindString(2, mName);
		this.insertStmt.bindLong(3, rate);
		this.insertStmt.bindLong(4, recommended);
		this.insertStmt.bindLong(5, sent);
		this.insertStmt.bindString(6, mDate);
		
		return this.insertStmt.executeInsert();
	}
	 
	public void deleteAll() {
		this.db.delete(TABLE_NAME, "1", null);
	}
	 
	public ArrayList<HistoryEntry> selectAll() {
		ArrayList<HistoryEntry> list = new ArrayList<HistoryEntry>();
		
		Cursor cursor = this.db.query(TABLE_NAME, new String[] {"_id", "name", "rate", "recommended", 
				"sent", "_date"}, null, null, null, null, "_date");
		
		if (cursor.moveToFirst()) {
			do {				
				HistoryEntry entry = new HistoryEntry();
				entry.setId(cursor.getString(0));
				entry.setName(cursor.getString(1));
				entry.setRate(cursor.getInt(2));
				entry.setRecommended(cursor.getInt(3));
				entry.setSent(cursor.getInt(4));
				entry.setDate(cursor.getString(5));
				
				list.add(entry);
				
			} while (cursor.moveToNext());
		}
		
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		
		Collections.sort(list, new Comparator<Object>(){
            public int compare(Object o1, Object o2) {
                HistoryEntry p1 = (HistoryEntry) o1;
                HistoryEntry p2 = (HistoryEntry) o2;
               return p1.getDate().compareTo(p2.getDate());
            }
        });
		
		return list;
	}
	
	public ArrayList<HistoryEntry> selectHistoryEntries (String filter) {
		ArrayList<HistoryEntry> list = new ArrayList<HistoryEntry>();

		Cursor cursor = this.db.query(TABLE_NAME, new String[] {"_id", "name", "rate", "recommended", 
				"sent", "_date"}, filter, null, null, null, "_date");
		
		if (cursor.moveToFirst()) {
			do {
				HistoryEntry entry = new HistoryEntry();
				entry.setId(cursor.getString(0));
				entry.setName(cursor.getString(1));
				entry.setRate(cursor.getInt(2));
				entry.setRecommended(cursor.getInt(3));
				entry.setSent(cursor.getInt(4));
				
				String date = cursor.getString(5).substring(0, 
						cursor.getString(5).indexOf("GMT"));
				entry.setDate(date, "EEE MMM dd HH:mm:ss");
				
				list.add(entry);
								
			} while (cursor.moveToNext());
		}
		
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}

		Collections.sort(list, new Comparator<Object>(){
            public int compare(Object o1, Object o2) {
            	if (o1 == null || o2 == null)
            		return -1;
            	
                HistoryEntry p1 = (HistoryEntry) o1;
                HistoryEntry p2 = (HistoryEntry) o2;
               return p1.getDate().compareTo(p2.getDate());
            }
        });

		return list;
	}

	public void createHistoryEntry(String id, String name, int rate, int recommended, int sent, String date) {
		try {
			insert(id, name, rate, recommended, sent, date);
			
		} catch (Exception e){
			e.printStackTrace();
			Toast.makeText(context, "error: " + e.getMessage(),
					Toast.LENGTH_LONG).show();
		}
	}
	
	public void createHistory(ArrayList<HistoryEntry> history) {
		
		for (HistoryEntry he : history) {
			insert(he.getId(), he.getName(), 0, 0, 0, he.getDate().toString());
		}
		
	}
	
	public void update(String id, float rating) {
		ContentValues cv = new ContentValues();
		cv.put("rate", rating);
		this.db.update(TABLE_NAME, cv, "_id = \'" + id + "\'", null);
	}
}
